<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import { debounce } from '@/utils'

export default {
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '200px'
    },
    dataArray: {
      type: Array,
      default: [
        { value: 0, name: '正常' },
        { value: 0, name: '故障' }
      ]
    }
  },
  watch:{
    dataArray (value){
      this.initChart()
    }
  },
  data() {
    return {
      chart: null
    }
  },
  mounted() {
    this.initChart()
    this.__resizeHandler = debounce(() => {
      if (this.chart) {
        this.chart.resize()
      }
    }, 100)
    window.addEventListener('resize', this.__resizeHandler)
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    window.removeEventListener('resize', this.__resizeHandler)
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      this.chart.setOption({
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          bottom: '5',
          left: 'center'
        },
        series: [
          {
            name: '正常与故障占比',
            type: 'pie',
            radius: ['45%', '70%'],
            center: ['50%', '40%'],
            avoidLabelOverlap: false,
            color:['#91cc75','#ee6666'],
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              formatter: '{b} : {c}'
            },
            emphasis: {
              label: {
                show: false,
                fontSize: '15',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: true
            },
            data: this.dataArray
          }
        ]
      })
    }
  }
}
</script>
